<!--
 * Copyright © 2022
 * @Author: zhangxiang
 * @Date: 2022-10-25 17:22:47
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-11-04 10:48:09
 * @Description:
 *
-->

<template>
  <div class="scaling-mgmt-ctn">
    <el-row type="flex" style="margin-bottom: 20px">
      <el-radio-group v-model="activeTab" size="small" @change="tabChange">
        <el-radio-button label="group">弹性伸缩组</el-radio-button>
        <el-radio-button label="config">伸缩配置</el-radio-button>
      </el-radio-group>
      <el-input
        v-model="searchKey"
        style="width: 200px; margin: 0 20px 0 30px"
        size="small"
        class="input"
        placeholder="请输入关键字进行过滤"
        clearable
        @clear="clearClick"
        @keyup.enter.native="queryClick"
      />
      <el-button
        size="small"
        type="primary"
        @click="queryClick"
      >查询</el-button>
      <el-button
        size="small"
        type="primary"
        style="margin-left: auto"
        icon="el-icon-plus"
        plain
        @click="addGroupClick"
      >创建弹性伸缩组</el-button>
      <el-button
        size="small"
        type="primary"
        icon="el-icon-plus"
        @click="addConfigClick"
      >创建伸缩配置</el-button>
    </el-row>
    <el-table
      v-if="activeTab === 'group'"
      key="group"
      class="scaling-table table-fixed"
      :data="list"
      header-cell-class-name="listHeaderCell"
      :header-cell-style="{ background: '#F3F3F3', color: '#696969' }"
      border
    >
      <el-table-column
        prop="provider"
        label="云商名称"
        min-width="110"
        show-overflow-tooltip=""
      >
        <template slot-scope="scope">
          {{ cloudVendorToChn(scope.row.provider) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="clusterName"
        label="集群名称"
        min-width="180"
        show-overflow-tooltip=""
      />
      <el-table-column
        prop="groupName"
        label="伸缩组名称"
        min-width="180"
        show-overflow-tooltip=""
      />
      <el-table-column prop="status" label="状态" min-width="100">
        <template slot-scope="scope">
          {{
            scope.row.status === 1
              ? "已启用"
              : scope.row.status === 2
                ? "已停用"
                : scope.row.status === 0
                  ? "初始"
                  : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="label"
        label="标签"
        min-width="130"
        show-overflow-tooltip=""
      />
      <el-table-column prop="deletePolicy" label="虚机移除原则" min-width="140">
        <template slot-scope="scope">
          {{ deletePolicyOptions[scope.row.deletePolicy] }}
        </template>
      </el-table-column>
      <el-table-column prop="clusterName" label="集群" min-width="170" />
      <el-table-column
        prop="configName"
        label="伸缩配置"
        min-width="170"
        show-overflow-tooltip=""
      />
      <el-table-column prop="currentNum" label="当前实例数" min-width="100" />
      <!-- <template slot-scope="scope">
        {{ cluserNodeNum }}
      </template> -->
      <!-- </el-table-column> -->
      <el-table-column prop="expectNum" label="期望实例数" min-width="100" />
      <el-table-column prop="minNum" label="最小实例数" min-width="100" />
      <el-table-column label="操作" width="230">
        <template slot-scope="scope">
          <!-- 初始状态且无策略 -->
          <template
            v-if="scope.row.status === 0 && scope.row.policyInfos.length === 0"
          >
            <el-button
              type="primary"
              size="mini"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              @click="addPolicyClick(scope.row)"
            >创建伸缩策略</el-button>
          </template>
          <!-- 初始状态已添加策略 -->
          <template
            v-if="scope.row.status === 0 && scope.row.policyInfos.length > 0"
          >
            <el-button
              type="primary"
              size="mini"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              @click="editPolicyClick(scope.row)"
            >编辑伸缩策略</el-button>
            <el-button
              type="primary"
              size="mini"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              @click="startPolicyClick(scope.row)"
            >启用</el-button>
          </template>
          <!-- 已启用 -->
          <template v-if="scope.row.status === 1">
            <el-button
              type="primary"
              size="mini"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              @click="viewPolicyClick(scope.row)"
            >查看伸缩策略</el-button>
            <el-button
              type="warning"
              size="mini"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              @click="stopPolicyClick(scope.row)"
            >停用</el-button>
          </template>
          <!-- 已停用 -->
          <template v-if="scope.row.status === 2">
            <el-button
              type="primary"
              size="mini"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              @click="editPolicyClick(scope.row)"
            >编辑伸缩策略</el-button>
            <el-button
              type="primary"
              size="mini"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              @click="startPolicyClick(scope.row)"
            >启用</el-button>
          </template>
          <!-- 除了已启用 都可以删除伸缩组 -->
          <el-popover
            :ref="`popover-delete-group-${scope.$index}`"
            placement="top"
            width="300"
            style="margin-left: 10px"
          >
            <p>是否确认删除该弹性伸缩组？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="
                  scope._self.$refs[
                    `popover-delete-group-${scope.$index}`
                  ].doClose()
                "
              >取消</el-button>
              <el-button
                type="primary"
                size="mini"
                @click="deleteGroupClick(scope)"
              >确定</el-button>
            </div>
            <el-button
              slot="reference"
              type="danger"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              size="mini"
              :disabled="scope.row.status === 1"
            >删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-table
      v-if="activeTab === 'config'"
      key="config"
      class="scaling-table table-fixed"
      :data="list"
      header-cell-class-name="listHeaderCell"
      :header-cell-style="{ background: '#F3F3F3', color: '#696969' }"
      border
    >
      <el-table-column
        prop="provider"
        label="云商名称"
        width="200"
        show-overflow-tooltip=""
      >
        <template slot-scope="scope">
          {{ cloudVendorToChn(scope.row.provider) }}
        </template>
      </el-table-column>
      />
      <el-table-column
        prop="configName"
        label="伸缩配置名称"
        show-overflow-tooltip=""
      />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            style="height: 22px; line-height: 22px; padding: 0 10px"
            @click="viewConfigClick(scope.row)"
          >查看伸缩配置</el-button>
          <el-popover
            :ref="`popover-delete-config-${scope.$index}`"
            placement="top"
            width="300"
            style="margin-left: 10px"
          >
            <p>是否确认删除该伸缩配置？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="
                  scope._self.$refs[
                    `popover-delete-config-${scope.$index}`
                  ].doClose()
                "
              >取消</el-button>
              <el-button
                type="primary"
                size="mini"
                @click="deleteConfigClick(scope)"
              >确定</el-button>
            </div>
            <el-button
              slot="reference"
              type="danger"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              size="mini"
            >删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-row type="flex" justify="end" style="margin-top: 25px">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :page-sizes="[10, 15, 20]"
        :page-size="pageSize"
        :current-page.sync="pageNum"
        :total="totalNum"
        @current-change="changePage"
        @size-change="sizeChange"
      />
    </el-row>

    <ScalingGroupDialog
      v-if="showScalingGroupDialog"
      :show.sync="showScalingGroupDialog"
      :info="groupDialogInfo"
      @success="addGroupSuccessCallback"
    />
    <ScalingConfigDialog
      v-if="showScalingConfigDialog"
      :show.sync="showScalingConfigDialog"
      :info="configDialogInfo"
      :is-create="configDialogCreate"
      @success="addConfigSuccessCallback"
    />
    <ScalingPolicyDialog
      v-if="showScalingPolicyDialog"
      :show.sync="showScalingPolicyDialog"
      :info="policyDialogInfo"
      :scene="policyDialogScene"
      @success="addPolicySuccessCallback"
    />
  </div>
</template>

<script>
import commonTab from '../mixin/commonTab'
// import { isEmptyString } from '@/utils'
import {
  getK8sClusterNodeInfos,
  getScalingGroupList,
  deleteScalingGroup,
  startScalingGroup,
  stopScalingGroup,
  getScalingConfigList,
  deleteScalingConfig
} from '@/api/cnap/hybrid-cloud'
import ScalingGroupDialog from './ScalingGroupDialog.vue'
import ScalingConfigDialog from './ScalingConfigDialog.vue'
import ScalingPolicyDialog from './ScalingPolicyDialog.vue'

export default {
  name: 'ScalingMgmt',
  components: {
    ScalingGroupDialog,
    ScalingConfigDialog,
    ScalingPolicyDialog
  },
  mixins: [commonTab],
  props: {},
  data() {
    return {
      // 移除原则
      deletePolicyOptions: {
        FIFO: '先创建先移除原则',
        LIFO: '后创建先移除原则'
      },
      activeTab: 'group',
      searchKey: '',
      cluserNodeNum: '',
      showScalingGroupDialog: false, // 伸缩组弹窗
      showScalingConfigDialog: false, // 伸缩配置弹窗
      configDialogCreate: true, // 创建伸缩配置 弹窗
      configDialogInfo: {}, // 伸缩配置弹窗 数据
      showScalingPolicyDialog: false, // 伸缩策略弹窗
      policyDialogScene: 1, // 伸缩策略弹窗 类型 1-创建 2-编辑 3-查看
      policyDialogInfo: {}
    }
  },
  computed: {
    /**
     * @description: 伸缩组弹窗所需信息
     * @return {*}
     */
    groupDialogInfo() {
      return {
        ...this.clusterParams,
        vpcId: this.commonInfo.vpcId,
        cluserNodeNum: this.cluserNodeNum
      }
    }
  },
  created() {},
  methods: {
    /**
     * @description: 创建弹性伸缩组成功回调
     * @return {*}
     */
    addGroupSuccessCallback() {
      this.getPageDataList()
    },
    /**
     * @description: 创建弹性伸缩组
     * @return {*}
     */
    addGroupClick() {
      this.showScalingGroupDialog = true
    },
    /**
     * @description: 创建伸缩配置成功回调
     * @return {*}
     */
    addConfigSuccessCallback() {
      this.getPageDataList()
    },
    /**
     * @description: 创建伸缩配置
     * @return {*}
     */
    addConfigClick() {
      this.configDialogInfo = {
        // ...this.clusterParams
      }
      this.configDialogCreate = true
      this.showScalingConfigDialog = true
    },
    /**
     * @description: 查看伸缩配置
     * @param {*} row
     * @return {*}
     */
    viewConfigClick(row) {
      this.configDialogInfo = {
        // ...this.clusterParams,
        ...row
      }
      this.configDialogCreate = false
      this.showScalingConfigDialog = true
    },
    /**
     * @description: 删除伸缩配置
     * @param {*} scope
     * @return {*}
     */
    deleteConfigClick(scope) {
      const row = scope.row
      deleteScalingConfig(row.configId).then((res) => {
        scope._self.$refs[`popover-delete-config-${scope.$index}`].doClose()
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.pageNum = Math.max(this.pageNum - 1, 1)
        }
        this.getPageDataList()
      })
    },
    /**
     * @description: 删除弹性伸缩组
     * @param {*} scope
     * @return {*}
     */
    deleteGroupClick(scope) {
      const row = scope.row
      deleteScalingGroup(row.id).then((res) => {
        scope._self.$refs[`popover-delete-group-${scope.$index}`].doClose()
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.pageNum = Math.max(this.pageNum - 1, 1)
        }
        this.getPageDataList()
      })
    },
    /**
     * @description: 创建伸缩策略成功回调
     * @return {*}
     */
    addPolicySuccessCallback() {
      this.getPageDataList()
    },
    /**
     * @description: 创建伸缩策略
     * @param {*} row
     * @return {*}
     */
    addPolicyClick(row) {
      this.policyDialogInfo = {
        groupId: row.id
      }
      this.policyDialogScene = 1
      this.showScalingPolicyDialog = true
    },
    /**
     * @description: 编辑伸缩策略
     * @param {*} row
     * @return {*}
     */
    editPolicyClick(row) {
      this.policyDialogInfo = {
        groupId: row.id,
        policyInfos: row.policyInfos || []
      }
      this.policyDialogScene = 2
      this.showScalingPolicyDialog = true
    },
    /**
     * @description: 查看伸缩策略
     * @param {*} row
     * @return {*}
     */
    viewPolicyClick(row) {
      this.policyDialogInfo = {
        groupId: row.id,
        policyInfos: row.policyInfos || []
      }
      this.policyDialogScene = 3
      this.showScalingPolicyDialog = true
    },
    /**
     * @description: 启用
     * @param {*} row
     * @return {*}
     */
    startPolicyClick(row) {
      startScalingGroup(row.id).then((res) => {
        this.$message.success('启用成功')
        this.getPageDataList()
      })
    },
    /**
     * @description: 停用
     * @param {*} row
     * @return {*}
     */
    stopPolicyClick(row) {
      stopScalingGroup(row.id).then((res) => {
        this.$message.success('停用成功')
        this.getPageDataList()
      })
    },
    /**
     * @description: 功能类别切换
     * @param {*} val
     * @return {*}
     */
    tabChange(val) {
      this.totalNum = 0
      this.list = []
      this.pageNum = 1
      this.getPageDataList()
    },
    /**
     * @description: 获取数据
     * @return {*}
     */
    getPageDataList() {
      // if (
      //   isEmptyString(this.commonInfo.cloudVendor) ||
      //   isEmptyString(this.commonInfo.k8sClusterName)
      // ) {
      //   // 云服务商 或者 集群为空 不请求
      //   return
      // }
      if (this.activeTab === 'group') {
        // this.getClusterNodeNum() // 更新当前实例数
        getScalingGroupList({
          provider: this.clusterParams.cloudVendor,
          accountName: this.clusterParams.accountName,
          clusterName: this.clusterParams.k8sClusterName,
          key: this.searchKey,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
          .then((res) => {
            if (res.data) {
              this.totalNum = res.data.totalNum
              this.list = Array.isArray(res.data.result) ? res.data.result : []
            } else {
              this.totalNum = 0
              this.list = []
            }
          })
          .finally(() => {
            this.loading = false
          })
      } else if (this.activeTab === 'config') {
        getScalingConfigList({
          provider: this.clusterParams.cloudVendor,
          accountName: this.clusterParams.accountName,
          clusterName: this.clusterParams.k8sClusterName,
          key: this.searchKey,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
          .then((res) => {
            if (res.data) {
              this.totalNum = res.data.totalNum
              this.list = Array.isArray(res.data.result) ? res.data.result : []
            } else {
              this.totalNum = 0
              this.list = []
            }
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    /**
     * @description: 每页显示size变化
     * @param {*} size
     * @return {*}
     */
    sizeChange(size) {
      this.pageSize = size
      this.pageNum = 1
      this.getPageDataList()
    },
    /**
     * @description: 当前页改变
     * @param {*} pageNum
     * @return {*}
     */
    changePage(pageNum) {
      this.pageNum = pageNum
      this.getPageDataList()
    },
    /**
     * @description: 清除关键字
     * @return {*}
     */
    clearClick() {
      this.searchKey = ''
      this.pageNum = 1
      this.getPageDataList()
    },
    /**
     * @description: 查询
     * @return {*}
     */
    queryClick() {
      this.pageNum = 1
      this.getPageDataList()
    },
    /**
     * @description: 获取集群下node数
     * @return {*}
     */
    getClusterNodeNum() {
      getK8sClusterNodeInfos({
        ...this.clusterParams,
        pageNo: 1,
        pageSize: 1
      }).then((res) => {
        this.cluserNodeNum = res.data ? res.data.totalNum || '' : ''
      })
    },
    /**
     * @description: 初始化
     * @return {*}
     */
    initTabData() {
      this.loading = true
      this.pageNum = 1
      this.getPageDataList()
    }
  }
}
</script>

<style lang="less" scoped>
.scaling-mgmt-ctn {
  .scaling-table {
    /deep/ .el-table::before {
      background-color: #e9e9e9;
    }
    /deep/ .listHeaderCell {
      height: 40px;
      padding: 0;
      box-sizing: border-box;
      &:first-child {
        padding-left: 20px;
      }
    }
    /deep/ .el-table__body {
      .el-table__row td {
        height: 40px;
        padding: 0;
        &:first-child {
          padding-left: 20px;
        }
      }
    }
  }
}
</style>
